<template>
  <PageCaontainer
    show-back
    :showCollapse="false"
    @back="router.go(-1)"
    class="dashboard-detail-wrapper"
  >
    <template #title>
      <span>{{ dashboardInfo.name }}</span>
      <span
        style="
          margin-left: 18px;
          color: #9b9fab;
          font-weight: normal;
          font-size: 14px;
        "
        >{{ 'ID: ' + route.params.id }}</span
      >
    </template>
    <template #extra>
      <a-space :size="10" v-if="route.params.type === '1'">
        <Edite :size="18" :strokeWidth="0" class="bg-icon" @click="toEdit" />
      </a-space>
    </template>
    <AGraphDetailPage
      v-model="graphData"
      :operateList="['date', 'info', 'spread']"
    >
      <template #contentTitle>
        <div class="detail-content-title">
          <a-button type="text" @click="globalFilterVisible = true"
            >全局筛选
          </a-button>
          <div class="title-items">
            <span
              v-show="globalFilterData.dateCondition.fixDate"
              class="show-filter-item"
              >{{ '日期：' + globalFilterData.dateCondition.fixDate }}</span
            >
            <template
              v-for="item in globalFilterData.conditions"
              :key="item.dimId"
            >
              <span v-if="item.dimId" class="show-filter-item">{{
                `${item.dimName}：${item.selectLabel.join('、')}`
              }}</span>
            </template>
          </div>
        </div>
      </template>
      <template #date="item">
        <component
          :is="
            getCurrentTimeComponent(
              item.cardConfig.metricsSetting.statisticalPeriod.type === 'recent'
                ? item.cardConfig.metricsSetting.statisticalPeriod.timeUnit
                : item.cardConfig.metricsSetting.statisticalPeriod.type
            )
          "
          v-model="item.cardConfig.dataTime"
          :style="{ width: '125px', marginRight: 0, border: 'none' }"
          @change="(val) => dataTimeChange(val, item)"
          :allow-clear="false"
        ></component>
      </template>
      <template #info="item">
        <a-popover
          v-if="item.cardConfig.type !== GraphType.NUMBER"
          content-class="metric-card-infoiconpop"
          position="bl"
        >
          <IconInfoCircle :size="18" style="color: #9b9fab; margin-top: 6px" />
          <template #content>
            <a-space direction="vertical" :size="12" fill>
              <a-space direction="vertical" :size="3">
                <span class="title">使用指标:</span>
                <span class="content keyword">{{ item.name }}</span>
              </a-space>
              <a-space direction="vertical" :size="3">
                <span class="title">业务含义:</span>
                <span class="content">{{ item.businessMeaning || '--' }}</span>
              </a-space>
              <a-space direction="vertical" :size="3">
                <span class="title">技术口径:</span>
                <span class="content">{{ item.caliber || '--' }}</span>
              </a-space>
              <div class="darken-content">
                <a-space direction="vertical" :size="12">
                  <a-space direction="vertical" :size="3">
                    <span class="title">统计周期:</span>
                    <span class="content">{{
                      mapStatisticalPeriodLabel(
                        item.cardConfig.metricsSetting.statisticalPeriod
                      )
                    }}</span>
                  </a-space>
                  <a-space
                    v-if="
                      item.cardConfig.metricsSetting.metricsConditions.length
                    "
                    direction="vertical"
                    :size="3"
                  >
                    <span class="title">附加限定条件:</span>
                    <template
                      v-for="(v, index) in item.cardConfig.metricsSetting
                        .metricsConditions"
                      :key="v.dimId"
                    >
                      <a-space>
                        <span class="keyword">{{ v.dimName }}</span>
                        <span class="content">{{
                          v.opType.toLowerCase()
                        }}</span>
                        <span class="content">{{
                          '(' + v.selectLabel.join('，') + ')'
                        }}</span>
                      </a-space>
                      <span
                        class="content"
                        v-if="
                          index !==
                          item.cardConfig.metricsSetting.metricsConditions
                            .length -
                            1
                        "
                        >{{
                          item.cardConfig.metricsSetting.rela.toLowerCase()
                        }}</span
                      >
                    </template>
                  </a-space>
                </a-space>
              </div>
            </a-space>
          </template>
        </a-popover>
      </template>
    </AGraphDetailPage>
  </PageCaontainer>
  <GlobalFilter
    v-model="globalFilterVisible"
    v-model:data="globalFilterData"
    @ok="globalOk"
  />
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import PageCaontainer from '@/arco-components/PageContainer';
import { IconInfoCircle } from '@arco-design/web-vue/es/icon';
import { Edite } from '@dangojs/digitforce-icons-vue';
import { AGraphDetailPage } from '@dangojs/a-graph-card';
import GlobalFilter from './components/globalFilter/index.vue';
import { GlobalFilterDataType } from './type';
import API from '@/services';
import * as RouteNames from '@/router/consts';
import { GraphType } from './type';
import {
  statisticalPeriodOption,
  statisticalPeriodUnitOption,
  defaultGlobalModel,
  TimeFrameType
} from './type';
import { Message } from '@arco-design/web-vue';
import {
  getCurrentTimeComponent,
  quarterTimeFormater,
  quarterFormater
} from './hooks';
import { cloneDeep } from 'lodash';

const router = useRouter();
const route = useRoute();

const graphData = ref<any[]>([]);
const globalFilterVisible = ref(false);
const dashboardInfo = reactive({
  name: '我的看板',
  description: ''
});

const globalFilterData = ref<GlobalFilterDataType>({
  conditions: [],
  dateCondition: {}
});

const currentGlobalModel = ref(defaultGlobalModel);

// 获取看板数据
const getListData = async (globalModel = defaultGlobalModel) => {
  globalModel.chosenMetricsIds = graphData.value.map((item) => item.id);
  let params: any = {
    boardId: +route.params.id,
    reviewType: 2,
    boardConfig: {
      ...globalModel
    }
  };
  const {
    code,
    data = {},
    msg
  } = await API.metricsBoard.postMetricsBoardView(params);
  if (code === 200) {
    dashboardInfo.name = data.name!;
    dashboardInfo.description = data.description!;
    graphData.value = (data.cards || []).map((item: any, index: number) => {
      quarterTimeFormater(item.cardConfig, TimeFrameType.MONTH);
      item.graphType = GraphType[item.cardConfig.type || 1];
      item.graphSize = item.graphType === 'NUMBER' ? 'SMALL' : 'MIDDLE';
      item.name = item.name;
      item.result = item.cardConfig.result;
      item.id = data.id;
      item.isFirst = item.cardConfig.isFirst;
      item.operateList = item.graphSize === 'SMALL' ? ['date'] : undefined;
      return item;
    });
  } else {
    Message.error(msg);
  }
};
getListData();

// 全局筛选点击确定
const globalOk = (data: any) => {
  currentGlobalModel.value = data;
  let d = cloneDeep(data);
  if (!d.dateCondition.fixDate) {
    d.dateCondition = null;
  }
  if (!d.dateCondition && !d.conditions.length) {
    return;
  }
  getListData(d);
};

// 跳转编辑页
const toEdit = () => {
  router.push({
    name: RouteNames.ROUTER_METRICS_DASHBOARD_EDIT,
    params: { id: route.params.id }
  });
};

// 切换单个时间
const dataTimeChange = async (val: any, item: any) => {
  let index = graphData.value.findIndex((v) => v.uuid === item.uuid);
  let params: any = {
    boardConfig: {
      chosenMetricsIds: [item.cardConfig.metricsSetting.metricsId],
      conditions: currentGlobalModel.value.conditions,
      dateCondition: {
        dateMode: 'FIXDATE',
        fixDate: val,
        offset: 0,
        timeUnit: item.cardConfig.metricsSetting.statisticalPeriod.timeUnit
      }
    },
    card: {
      cardConfig: item.cardConfig,
      name: item.name
    }
  };
  if (params.boardConfig.dateCondition.timeUnit === TimeFrameType.QUARTER) {
    params.boardConfig.dateCondition.fixDate = quarterFormater(
      params.boardConfig.dateCondition.fixDate,
      TimeFrameType.QUARTER
    );
    params.boardConfig.dateCondition.fixDate = quarterFormater(
      params.boardConfig.dateCondition.fixDate,
      TimeFrameType.QUARTER
    );
  }
  delete params.card.cardConfig.result;
  const {
    code,
    data = {},
    msg
  } = await API.metricsBoard.postMetricsBoardCardPreview(params);
  if (code === 200) {
    quarterTimeFormater(data.cardConfig, TimeFrameType.MONTH);
    let detail: any = {
      graphSize:
        data.cardConfig!.type === GraphType.NUMBER ? 'SMALL' : 'MIDDLE',
      graphType: GraphType[data.cardConfig!.type || 1],
      name: data.name,
      cardConfig: data.cardConfig,
      result: (data.cardConfig! as any).result,
      operateList:
        data.cardConfig!.type === GraphType.NUMBER ? ['date'] : undefined
    };
    graphData.value.splice(index, 1, cloneDeep(detail));
  } else {
    Message.error(msg);
  }
};
// 匹配统计周期文字
const mapStatisticalPeriodLabel = (data: any) => {
  let label =
    (statisticalPeriodOption.find((item) => item.value === data.type) || {})
      .label || '当日';
  let unitLabel =
    (
      statisticalPeriodUnitOption.find(
        (item) => item.value === data.timeUnit
      ) || {}
    ).label || '日';
  if (data.type === 'recent') {
    return label + data.offset + unitLabel;
  }
  return label;
};
</script>

<style lang="scss" scoped>
.dashboard-detail-wrapper {
  .detail-content-title {
    display: flex;
    align-items: center;
    padding: 0 9px 8px 9px;

    .title-items {
      flex: 1;
      line-height: 24px;
      margin-left: 26px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #60646f;
      .show-filter-item {
        padding: 0 10px;
      }
      .show-filter-item:not(:last-child) {
        border-right: 1px solid #60646f;
      }
    }
  }
  .bg-icon {
    width: 30px;
    height: 30px;
    padding: 6px;
    color: #60646f;
    font-size: 18px;
    background-color: #f6f8fc;
    border-radius: 3px;
    cursor: pointer;
    box-sizing: border-box;
  }
}
</style>

<style lang="scss">
.dashboard-detail-wrapper {
  .arco-popover-popup-arrow {
    display: block;
  }
  .arco-trigger-arrow {
    width: 12px;
    height: 12px;
  }
  .card-drag-center * {
    box-sizing: border-box;
  }
  .a-page-container {
    position: fixed;
    top: 0;
    z-index: 11;
  }
  .a-page-container-header {
    border-bottom: 1px solid #eee;
    box-shadow: 0px 3px 6px 0px rgba(51, 53, 59, 0.06);
    height: 60px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .a-page-container-page-header {
      flex: 1;
      padding: 0;
    }
    .arco-page-header-wrapper {
      padding: 0 18px;
    }
  }
  .a-page-container-content {
    padding-left: 9px;
    padding-right: 9px;
    overflow: auto;
  }
}

.graph-content,
.graph-wrapper {
  box-sizing: border-box;
}

.metric-card-infoiconpop {
  max-width: 270px;
  min-width: 200px;
  padding: 12px;
  .arco-popover-content {
    margin-top: 0;
  }
  .title {
    font-size: 12px;
    color: #60646f;
    line-height: 20px;
  }
  .content {
    font-size: 12px;
    color: #33353b;
    line-height: 20px;
  }
  .keyword {
    color: rgb(var(--primary-6));
  }
  .darken-content {
    width: 100%;
    box-sizing: border-box;
    padding: 10px;
    background: #f6f8fc;
    border-radius: 3px;
  }
}

.card-title-container .card-title-right .operate-list .operate-item {
  padding: 0;
}
.arco-modal.info-modal-container .arco-modal-body {
  padding: 18px;
  box-sizing: border-box;
  .graph-content {
    padding: 0;
  }
}
</style>
